﻿using Coway.Ordering.Orders;
using Coway.Ordering.PayOrders;
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Graphics;
using Spire.Pdf.Widget;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Security.Encryption;

namespace Coway.Ordering.Pdfs
{
    /// <summary>
    /// PDF表单帮助类
    /// </summary>
    public class PDFFormHelper : ITransientDependency
    {
        private readonly IStringEncryptionService _stringEncryptionService;
        public PDFFormHelper(
            IStringEncryptionService stringEncryptionService)
        {
            _stringEncryptionService = stringEncryptionService;
        }

        public byte[] FileOrder(ExportOrderDto dto, byte[] signImages)
        {
            dto.Buyer.SocialSecurityNumber = _stringEncryptionService.Decrypt(dto.Buyer.SocialSecurityNumber);
            dto.Buyer.SocialSecurityNumber = dto.Buyer.SocialSecurityNumberFormat();

            dto.InstallationInfo.HomePhone = dto.InstallationInfo.HomePhoneFormat();
            dto.InstallationInfo.Mobile = dto.InstallationInfo.MobileFormat();
            dto.Buyer.HomePhone = dto.Buyer.HomePhoneFormat();
            dto.Buyer.Mobile = dto.Buyer.MobileFormat();

            OrderItemDto item1 = null;
            if (dto.OrderItems.Count >= 1)
            {
                item1 = dto.OrderItems[0];
            }

            OrderItemDto item2 = null;
            if (dto.OrderItems.Count >= 2)
            {
                item2 = dto.OrderItems[1];
            }

            OrderItemDto item3 = null;
            if (dto.OrderItems.Count >= 3)
            {
                item3 = dto.OrderItems[2];
            }

            PdfDocument doc = new PdfDocument();
            var tplPath = Path.Combine(Directory.GetCurrentDirectory(),
                "ExportTemplates", "Application.pdf");
            doc.LoadFromFile(tplPath);
            PdfFormWidget formWidget = doc.Form as PdfFormWidget;
            for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
            {
                PdfField field = formWidget.FieldsWidget.List[i] as PdfField;
                if (field is PdfTextBoxFieldWidget)
                {
                    PdfTextBoxFieldWidget textBoxField = field as PdfTextBoxFieldWidget;
                    switch (textBoxField.Name)
                    {
                        //CUSTOMER INFORMATION部分
                        case "First Name":
                            textBoxField.Text = dto.Buyer.FirstName ?? "";
                            break;
                        case "Last Name":
                            textBoxField.Text = dto.Buyer.LastName ?? "";
                            break;
                        case "Social No"://社安号
                            textBoxField.Text = dto.Buyer.SocialSecurityNumber ?? "";
                            break;
                        case "DOB":
                            // 出生年月日
                            textBoxField.Text = dto.Buyer.DateOfBirth.HasValue ? dto.Buyer.DateOfBirth.Value.ToString("MM/dd/yyyy") : "";
                            break;
                        case "EMAIL":
                            textBoxField.Text = dto.Buyer.EMail ?? "";
                            break;
                        case "TAX ID"://TAX ID / BUSINESS REGISTRATION NUMBER
                            textBoxField.Text = dto.Buyer.TaxId ?? "";
                            break;
                        //LEGAL ADDRESS /RESIDENCE
                        case "Street1":
                            textBoxField.Text = dto.Buyer.LegalAddressStreet ?? "";
                            break;
                        case "AptNum1":
                            textBoxField.Text = dto.Buyer.LegalAddressApt ?? "";
                            break;
                        case "City1":
                            textBoxField.Text = dto.Buyer.LegalAddressCity ?? "";
                            break;
                        case "State1":
                            textBoxField.Text = dto.Buyer.LegalAddressState ?? "";
                            break;
                        case "ZIP1":
                            textBoxField.Text = dto.Buyer.LegalAddressZipCode ?? "";
                            break;
                        //BILLING ADDRESS
                        case "Street2":
                            textBoxField.Text = dto.Buyer.BillingAddressStreet ?? "";
                            break;
                        case "AptNum2":
                            textBoxField.Text = dto.Buyer.BillingAddressApt ?? "";
                            break;
                        case "City2":
                            textBoxField.Text = dto.Buyer.BillingAddressCity ?? "";
                            break;
                        case "State2":
                            textBoxField.Text = dto.Buyer.BillingAddressState ?? "";
                            break;
                        case "ZIP2":
                            textBoxField.Text = dto.Buyer.BillingAddressZipCode ?? "";
                            break;
                        //NSTALLATION ADDRESS
                        case "Street3":
                            textBoxField.Text = dto.InstallationInfo.AddressStreet ?? "";
                            break;
                        case "AptNum3":
                            textBoxField.Text = dto.InstallationInfo.AddressApt ?? "";
                            break;
                        case "City3":
                            textBoxField.Text = dto.InstallationInfo.AddressCity ?? "";
                            break;
                        case "State3":
                            textBoxField.Text = dto.InstallationInfo.AddressState ?? "";
                            break;
                        case "ZIP3":
                            textBoxField.Text = dto.InstallationInfo.AddressZipCode ?? "";
                            break;

                        case "Home Ph1":
                            textBoxField.Text = dto.Buyer.HomePhone ?? "";
                            break;
                        case "Mobile1":
                            textBoxField.Text = dto.Buyer.Mobile ?? "";
                            break;
                        case "Home Ph2":
                            textBoxField.Text = dto.InstallationInfo.HomePhone ?? "";
                            break;
                        case "Mobile2":
                            textBoxField.Text = dto.InstallationInfo.Mobile ?? "";
                            break;

                        case "NAME OF SALES REP":
                            textBoxField.Text = dto.SellerName ?? "";
                            break;
                        case "RepPhone":
                            textBoxField.Text = dto.SellerPhone ?? "";
                            break;
                        case "Sales Rep Code":
                            textBoxField.Text = dto.SellerCode ?? "";
                            break;
                        case "REQUEST DATE":
                            textBoxField.Text = dto.InstallationInfo.RequestDate.HasValue ? dto.InstallationInfo.RequestDate.Value.ToString("MM/dd/yyyy") : "";
                            break;
                        case "First Name 2":
                            textBoxField.Text = dto.InstallationInfo.FirstName ?? "";
                            break;
                        case "Last Name 2":
                            textBoxField.Text = dto.InstallationInfo.LastName ?? "";
                            break;
                        case "MEMBERSHIP":
                            textBoxField.Text = dto.InstallationInfo.Membership ?? "";
                            break;
                        case "REMARK":
                            //PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 11);
                            Font font = new Font("Microsoft Yahei",7, FontStyle.Regular);
                            textBoxField.Font = new PdfTrueTypeFont(font, true);
                            textBoxField.Text = dto?.Remarks ?? "";
                            break;


                        //产品部分1
                        case "MODEL1":
                            textBoxField.Text = item1?.Model ?? "";
                            break;
                        case "QUANTITY1":
                            textBoxField.Text = item1 != null ? item1.Quantity.ToString() : "";
                            break;
                        case "Years1":
                            textBoxField.Text = item1?.ContractDuration?.ToString() ?? "";
                            break;
                        case "REGISTRATION FEE1":
                            textBoxField.Text = item1?.RegistrationFee?.ToString() ?? "";
                            break;
                        case "MONTHLY RENT WO TAXYears1":
                            textBoxField.Text = item1?.MonthlyRent?.ToString() ?? "";
                            break;
                        case "SALES PRICE WO TAXYears1":
                            textBoxField.Text = item1?.SalesPrice?.ToString() ?? "";
                            break;
                        case "TAXYears1":
                            textBoxField.Text = item1?.OrderTax?.ToString() ?? "";
                            break;
                        case "TOTAL USDYears1":
                            textBoxField.Text = item1?.Total?.ToString() ?? "";
                            break;
                        //产品部分2
                        case "MODEL2":
                            textBoxField.Text = item2?.Model ?? "";
                            break;
                        case "QUANTITY2":
                            textBoxField.Text = item2 != null ? item2.Quantity.ToString() : "";
                            break;
                        case "Years2":
                            textBoxField.Text = item2?.ContractDuration?.ToString() ?? "";
                            break;
                        case "REGISTRATION FEE2":
                            textBoxField.Text = item2?.RegistrationFee?.ToString() ?? "";
                            break;
                        case "MONTHLY RENT WO TAXYears2":
                            textBoxField.Text = item2?.MonthlyRent?.ToString() ?? "";
                            break;
                        case "SALES PRICE WO TAXYears2":
                            textBoxField.Text = item2?.SalesPrice?.ToString() ?? "";
                            break;
                        case "TAXYears2":
                            textBoxField.Text = item2?.OrderTax?.ToString() ?? "";
                            break;
                        case "TOTAL USDYears2":
                            textBoxField.Text = item2?.Total?.ToString() ?? "";
                            break;
                        //产品部分3
                        case "MODEL3":
                            textBoxField.Text = item3?.Model ?? "";
                            break;
                        case "QUANTITY3":
                            textBoxField.Text = item3 != null ? item3.Quantity.ToString() : "";
                            break;
                        case "Years3":
                            textBoxField.Text = item3?.ContractDuration?.ToString() ?? "";
                            break;
                        case "REGISTRATION FEE3":
                            textBoxField.Text = item3?.RegistrationFee?.ToString() ?? "";
                            break;
                        case "MONTHLY RENT WO TAXYears3":
                            textBoxField.Text = item3?.MonthlyRent?.ToString() ?? "";
                            break;
                        case "SALES PRICE WO TAXYears3":
                            textBoxField.Text = item3?.SalesPrice?.ToString() ?? "";
                            break;
                        case "TAXYears3":
                            textBoxField.Text = item3?.OrderTax?.ToString() ?? "";
                            break;
                        case "TOTAL USDYears3":
                            textBoxField.Text = item3?.Total?.ToString() ?? "";
                            break;
                        case "Date1":
                            textBoxField.Text = DateTime.Now.ToString("yyyy/MM/dd");
                            break;
                        //签名部分
                        case "Signature1_es_:signature":
                            //加载缩放后的图片到PdfImage对象
                            if (signImages != null)
                            {
                                PdfImage pdfImage = PdfImage.FromStream(new MemoryStream(signImages));

                                //设置图片位置
                                float x = 148f;
                                float y = 700f;
                                doc.Pages[0].Canvas.DrawImage(pdfImage, x, y, 180, 40);
                            }
                            break;
                    }
                }

                if (field is PdfCheckBoxWidgetFieldWidget)
                {
                    PdfCheckBoxWidgetFieldWidget checkBoxField = field as PdfCheckBoxWidgetFieldWidget;
                    switch (checkBoxField.Name)
                    {
                        case "OPTIONYes":
                            checkBoxField.Checked = dto.InstallationInfo?.Option == "YES";
                            break;
                        case "OPTIONNo":
                            checkBoxField.Checked = dto.InstallationInfo?.Option == "NO";
                            break;
                        case "ACH":
                            checkBoxField.Checked = item1?.MonthlyPaymentMethod == "ACH";
                            break;
                        case "CCR":
                            checkBoxField.Checked = item1?.MonthlyPaymentMethod == "CCR";
                            break;
                        case "Check Reason":
                            checkBoxField.Checked = item1?.MonthlyPaymentMethod == "CHECK";
                            break;
                    }
                }
            }

            using (MemoryStream ms = new MemoryStream())
            {
                doc.SaveToStream(ms);
                byte[] buffer = new byte[ms.Length];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Flush();
                ms.Read(buffer, 0, (int)ms.Length);

                return buffer;
            }
        }

        public byte[] FillCCRPayOrder(CCRPayOrder payOrder, byte[] signImages = null)
        {
            payOrder.CardNo = _stringEncryptionService.Decrypt(payOrder.CardNo);
            payOrder.CVV = _stringEncryptionService.Decrypt(payOrder.CVV);

            PdfDocument doc = new PdfDocument();
            var tplPath = Path.Combine(Directory.GetCurrentDirectory(),
                "ExportTemplates", "CREDITCARD.pdf");
            doc.LoadFromFile(tplPath);
            PdfFormWidget formWidget = doc.Form as PdfFormWidget;
            for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
            {
                PdfField field = formWidget.FieldsWidget.List[i] as PdfField;
                if (field is PdfTextBoxFieldWidget)
                {
                    PdfTextBoxFieldWidget textBoxField = field as PdfTextBoxFieldWidget;
                    switch (textBoxField.Name)
                    {
                        case "CARD":
                            textBoxField.Text = payOrder.CardNo ?? "";
                            break;
                        case "EXPIRATION DATE":
                            textBoxField.Text = payOrder.ExpirationDate.HasValue ? payOrder.ExpirationDate.Value.ToString("MM/yyyy") : "";
                            break;
                        case "CVV":
                            textBoxField.Text = payOrder.CVV ?? "";
                            break;
                        case "CARD HOLDER NAME":
                            textBoxField.Text = payOrder.CardHolderName ?? "";
                            break;
                        case "ORDER ":
                            textBoxField.Text = "";
                            break;
                        case "AMOUNT":
                            textBoxField.Text = payOrder.Amount.HasValue ? ("$"+payOrder.Amount.Value.ToString()) : "";
                            break;
                        case "BILLING ADDRESS":
                            textBoxField.Text = $"{payOrder.BillingAddressApt} {payOrder.BillingAddressStreet} {payOrder.BillingAddressCity} {payOrder.BillingAddressState}";
                            break;
                        case "ZIP CODE":
                            textBoxField.Text = payOrder.BillingAddressZipCode ?? "";
                            break;
                        case "REMARK":
                            Font font = new Font("Microsoft Yahei", 7, FontStyle.Regular);
                            textBoxField.Font = new PdfTrueTypeFont(font, true);
                            textBoxField.Text = payOrder.Remark ?? "";
                            break;
                        case "DATE":
                            textBoxField.Text = payOrder.Date.HasValue ? payOrder.Date.Value.ToString("MM/dd/yyyy") : "";
                            break;
                        case "CONTACT":
                            textBoxField.Text = payOrder.Contact ?? "";
                            break;
                        case "RECEIVER":
                            textBoxField.Text = payOrder.Receiver ?? "";
                            break;
                        case "Signature_es_:signer:signature":

                            //Image image = Image.FromFile(@"logo.png");
                            ////调整图片大小
                            //int width = 100;
                            //int height = 35;
                            //float scale = 0.8f;  //缩放比例
                            //Size size = new Size((int)(width * scale), (int)(height * scale));
                            //Bitmap scaledImage = new Bitmap(image, size);

                            ////加载缩放后的图片到PdfImage对象
                            //PdfImage pdfImage = PdfImage.FromStream(new MemoryStream(Convert.FromBase64String(payOrder.SignatureImage)));

                            //////设置图片位置
                            //float x = 225f;
                            //float y = 573f;
                            //doc.Pages[0].Canvas.DrawImage(pdfImage, x, y);

                            //加载缩放后的图片到PdfImage对象
                            if (signImages != null)
                            {
                                PdfImage pdfImage = PdfImage.FromStream(new MemoryStream(signImages));

                                //设置图片位置
                                float x = 225f;
                                float y = 573f;
                                doc.Pages[0].Canvas.DrawImage(pdfImage, x, y, 100, 35);
                            }
                            break;
                    }
                }

                if (field is PdfCheckBoxWidgetFieldWidget)
                {
                    PdfCheckBoxWidgetFieldWidget checkBoxField = field as PdfCheckBoxWidgetFieldWidget;
                    switch (checkBoxField.Name)
                    {
                        case "VISA":
                            checkBoxField.Checked = payOrder.CardType == "Visa";
                            break;
                        case "MASTER":
                            checkBoxField.Checked = payOrder.CardType == "MasterCard";
                            break;
                        case "DISCOVER":
                            checkBoxField.Checked = payOrder.CardType == "Discover";
                            break;
                    }
                }
            }

            using (MemoryStream ms = new MemoryStream())
            {
                doc.SaveToStream(ms);
                byte[] buffer = new byte[ms.Length];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Flush();
                ms.Read(buffer, 0, (int)ms.Length);

                return buffer;
            }
        }

        public byte[] FillACHPayOrder(ACHPayOrder payOrder, ExportOrderDto orderDto, byte[] signImages = null, byte[] payImages = null)
        {
            payOrder.CardNo = _stringEncryptionService.Decrypt(payOrder.CardNo);
            payOrder.CVV = _stringEncryptionService.Decrypt(payOrder.CVV);

            PdfDocument doc = new PdfDocument();
            var tplPath = Path.Combine(Directory.GetCurrentDirectory(),
                "ExportTemplates", "ACH CCR FORM.pdf");
            doc.LoadFromFile(tplPath);
            PdfFormWidget formWidget = doc.Form as PdfFormWidget;
            if (payImages != null)
            {
                //加载缩放后的图片到PdfImage对象
                PdfImage pdfImage = PdfImage.FromStream(new MemoryStream(payImages));
                float x = 60f;
                float y = 280f;
                doc.Pages[0].Canvas.DrawImage(pdfImage, x, y, 450, 150);
            }
            for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
            {
                PdfField field = formWidget.FieldsWidget.List[i] as PdfField;
                if (field is PdfTextBoxFieldWidget)
                {
                    PdfTextBoxFieldWidget textBoxField = field as PdfTextBoxFieldWidget;
                    switch (textBoxField.Name)
                    {
                        case "Customer Name":
                            textBoxField.Text = payOrder.CustomerName ?? "";
                            break;
                        case "Phone":
                            textBoxField.Text = payOrder.Phone ?? "";
                            break;
                        case "Address":
                            textBoxField.Text = payOrder.Address ?? "";
                            break;
                        case "Card Holder Name":
                            textBoxField.Text = payOrder.CardHolderName ?? "";
                            if (payImages != null)
                            {
                                textBoxField.ReadOnly = true;
                            }
                            break;
                        case "Card Number":
                            textBoxField.Text = payOrder.CardNo ?? "";
                            if (payImages != null)
                            {
                                textBoxField.ReadOnly = true;
                            }
                            break;
                        case "Expiration Date":
                            textBoxField.Text = payOrder.ExpirationDate.HasValue ? payOrder.ExpirationDate.Value.ToString("MM/yyyy") : "";
                            if (payImages != null)
                            {
                                textBoxField.ReadOnly = true;
                            }
                            break;
                        case "Billing Address":
                            textBoxField.Text = $"{payOrder.BillingAddressApt} {payOrder.BillingAddressStreet} {payOrder.BillingAddressCity} {payOrder.BillingAddressState} {payOrder.BillingAddressZipCode}";
                            if (payImages != null)
                            {
                                textBoxField.ReadOnly = true;
                            }
                            break;
                        case "CVV#":
                            textBoxField.Text = payOrder.CVV ?? "";
                            if (payImages != null)
                            {
                                textBoxField.ReadOnly = true;
                            }
                            break;
                        case "DATE":
                            textBoxField.Text = payOrder.Date.HasValue ? payOrder.Date.Value.ToString("MM/dd/yyyy") : "";
                            if (payImages != null)
                            {
                                textBoxField.ReadOnly = true;
                            }
                            break;
                        case "Remark":
                            //需要传输业务填写的remark
                            //需要写中文字段前面增加下面两行
                            Font font = new Font("Microsoft Yahei", 8, FontStyle.Regular);
                            textBoxField.Font = new PdfTrueTypeFont(font, true);
                            textBoxField.Text = orderDto?.Remarks ?? "";
                            textBoxField.ReadOnly = true;
                            break;
                        case "Signature1_es_:signer:signature":
                            //加载缩放后的图片到PdfImage对象
                            if (signImages != null)
                            {
                                PdfImage pdfImage = PdfImage.FromStream(new MemoryStream(signImages));

                                //设置图片位置
                                float x = 141f;
                                float y = 668f;
                                doc.Pages[0].Canvas.DrawImage(pdfImage, x, y, 180, 42);
                            }
                            break;
                    }
                }

                if (field is PdfCheckBoxWidgetFieldWidget)
                {
                    PdfCheckBoxWidgetFieldWidget checkBoxField = field as PdfCheckBoxWidgetFieldWidget;
                    switch (checkBoxField.Name)
                    {
                        case "10th":
                            checkBoxField.Checked = payOrder.PaymentDate == "10th";
                            break;
                        case "15th":
                            checkBoxField.Checked = payOrder.PaymentDate == "15th";
                            break;
                        case "20th":
                            checkBoxField.Checked = payOrder.PaymentDate == "20th";
                            break;
                        case "Visa":
                            checkBoxField.Checked = payOrder.CardType == "Visa";
                            if (payImages != null)
                            {
                                checkBoxField.ReadOnly = true;
                            }
                            break;
                        case "Master Card":
                            checkBoxField.Checked = payOrder.CardType == "MasterCard";
                            if (payImages != null)
                            {
                                checkBoxField.ReadOnly = true;
                            }
                            break;
                        case "Discover":
                            checkBoxField.Checked = payOrder.CardType == "Discover";
                            if (payImages != null)
                            {
                                checkBoxField.ReadOnly = true;
                            }
                            break;
                    }
                }
            }

            using (MemoryStream ms = new MemoryStream())
            {
                doc.SaveToStream(ms);
                byte[] buffer = new byte[ms.Length];
                ms.Seek(0, SeekOrigin.Begin);
                ms.Flush();
                ms.Read(buffer, 0, (int)ms.Length);

                return buffer;
            }
        }
    }
}
